package com.demo.sender.email;

import com.demo.annotation.EmailChannel;
import com.demo.common.ResultData;
import com.demo.enums.EmailChannelEnum;
import com.demo.request.EmailSenderReq;
import com.mailgun.api.v3.MailgunMessagesApi;
import com.mailgun.model.message.Message;
import com.mailgun.model.message.MessageResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author wangfengchen
 * 文档地址：<a href="https://github.com/mailgun/mailgun-java">https://github.com/mailgun/mailgun-java</a>
 * <a href="https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/#examples">https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/#examples</a>
 */
@EmailChannel(channel = EmailChannelEnum.MAILGUN)
@Component
@Slf4j
public class MailGunEmailSender implements EmailSenderService {


  //  private static final String url = "https://api.mailgun.net/v3/email.newhuotech.com/messages";

  @Value("${email.mailGun.source:not_set}")
  private String source;
  @Value("${email.mailGun.domain:not_set}")
  private String domain;

  @Autowired
  private MailgunMessagesApi mailgunMessagesApi;
  @Autowired
  private MailgunMessagesApi mailgunAsyncMessagesApi;


  /**
   * 发送邮件
   *
   * @param request
   * @return
   */
  @Override
  public ResultData<Object> send(EmailSenderReq request) {
    if (StringUtils.isBlank(request.getBodyText()) && StringUtils.isBlank(request.getBodyHtml())) {
      log.error("发送内容为空");
      return null;
    }
    Message message = Message.builder()
        .from(source)
        .to(request.getToList())
        .subject(request.getSubject())
        .text(request.getBodyText())
        .html(request.getBodyHtml())
        .build();
    MessageResponse messageResponse = mailgunMessagesApi.sendMessage(domain, message);
    log.info("response = {}", messageResponse);
    return ResultData.success(messageResponse.getId());
  }

  /**
   * 异步发送邮件
   *
   * @param request
   * @return
   */
  @Override
  public ResultData<Object> sendAsync(EmailSenderReq request) {
    if (StringUtils.isBlank(request.getBodyText()) && StringUtils.isBlank(request.getBodyHtml())) {
      log.error("发送内容为空");
      return null;
    }
    Message message = Message.builder()
        .from(source)
        .to(request.getToList())
        .subject(request.getSubject())
        .text(request.getBodyText())
        .html(request.getBodyHtml())
        .build();
    CompletableFuture<MessageResponse> result = mailgunAsyncMessagesApi.sendMessageAsync(domain, message);
    if (ObjectUtils.isEmpty(result)) {
      return ResultData.fail();
    }
    String messageId = null;
    try {
      messageId = result.get().getId();
    } catch (InterruptedException | ExecutionException e) {
      throw new RuntimeException(e);
    }
    return ResultData.success(messageId);
  }

  @Override
  public void sendWithAttachmentAsync(EmailSenderReq request) {
    Message message = Message.builder()
        .from(source)
        .to(request.getToList())
        .subject(request.getSubject())
        .text(request.getBodyText())
        .html(request.getBodyHtml())
//        .attachment()
        .build();
    CompletableFuture<MessageResponse> result = mailgunAsyncMessagesApi.sendMessageAsync(domain, message);
    if (ObjectUtils.isNotEmpty(result)) {
      try {
        String messageId = result.get().getId();
        log.info("邮件发送成功，messageId = {}", messageId);
      } catch (InterruptedException | ExecutionException e) {
        log.error("邮件发送失败，exception = {}", ExceptionUtils.getStackTrace(e));
        throw new RuntimeException(e);
      }
    }
  }

  /**
   * 处理发送邮件异常
   *
   * @param e           异常对象
   * @param toAddresses
   */
  private void handleSendEmailException(Exception e, List<String> toAddresses) {
    // 这里可以添加自定义的日志记录或异常处理逻辑
    log.info("handleSendEmailException error，toAddresses = {}，error = {}", toAddresses, ExceptionUtils.getStackTrace(e));
    // 其他业务处理
  }


}

